package main

import (
	"encoding/json"
	"fmt"
)

type Monster struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func (monster *Monster) String() string {
	return fmt.Sprintf("{name:%vage:%v}", monster.Name, monster.Age)
}

/**
data json数组,inter万能接口 传入要转换的struct类型
*/
func unmarshalStruct(data []byte, inter interface{}) {

	// 反序列化
	err := json.Unmarshal(data, inter)

	if err != nil {
		// 输入错误,并终止程序
		panic(err)
	}

}

func main() {

	monster := Monster{"哈士奇", 4}
	// json.Marshal转换时, struct 小写开头字段(私有)识别不到
	data, _ := json.Marshal(monster)
	var monster1 Monster
	unmarshalStruct(data, &monster1)
	fmt.Printf("monster1 =%v \n", &monster1)
	// map反序列化
	var mapObj map[string]interface{}

	unmarshalStruct(data, &mapObj)
	fmt.Printf("mapObj =%v \n", mapObj)

	// 切片序列化
	var slice []map[string]interface{}

	slice = append(slice, mapObj)
	data1, _ := json.Marshal(slice)
	var slice1 []map[string]interface{}

	unmarshalStruct(data1, &slice1)
	fmt.Printf("slice1 =%v", slice1)

}
